package cn.edu.huas.shopping.dao;

import cn.edu.huas.shopping.exception.DaoException;
import cn.edu.huas.shopping.pojo.User;
import cn.edu.huas.shopping.utils.DBUtils;

import java.sql.*;

public class UserDaoImpl implements UserDao{


    @Override
    public void insertUser(User user) throws DaoException {
        final String sql="insert into t_user(username,pwd) values(?,?)";
        try {
            DBUtils.update(sql,user.getUsername(),user.getPwd());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public User queryByUsername(String username) throws DaoException {
        String sql="select id,username,pwd,dotime from t_user where username=? ";
        return DBUtils.query(sql, rs->{
            User u=null;
            if (rs.next()){
                u=new User();
                Integer id=rs.getInt("id");
                String name=rs.getString("username");
                String pwd=rs.getString("pwd");
                Timestamp timestamp=rs.getTimestamp("dotime");
                u.setId(id);
                u.setUsername(name);
                u.setPwd(pwd);
                u.setDoTime(timestamp.toLocalDateTime());
            }
            return u;
        },username );
    }

    @Override
    /*public User queryByUsernameAndPwd(String username, String pwd) throws DaoException {
        String sql="select id,username,dotime from t_user where username=? and pwd=?";
        return DBUtils.query(sql, new RowMapper<User>() {

            @Override
            public User parseResultSet(ResultSet rs) throws SQLException{
                User u=null;
                    if (rs.next()){
                        u=new User();
                        Integer id=rs.getInt("id");
                        String name=rs.getString("username");
                        Timestamp timestamp=rs.getTimestamp("dotime");
                        u.setId(id);
                        u.setUsername(name);
                        u.setDoTime(timestamp.toLocalDateTime());
                    }
                    return u;
            }
        },username,pwd);
    }*/
    public User queryByUsernameAndPwd(String username, String pwd) throws DaoException {
        String sql="select id,username,pwd,dotime from t_user where username=? and pwd=?";
        return DBUtils.query(sql, rs->{
            User u=null;
            if (rs.next()){
                u=new User();
                Integer id=rs.getInt("id");
                String name=rs.getString("username");
                Timestamp timestamp=rs.getTimestamp("dotime");
                u.setId(id);
                u.setUsername(name);
                u.setPwd(pwd);
                u.setDoTime(timestamp.toLocalDateTime());
            }
            return u;
        },username,pwd);
    }
}
